package rmhc.api.fb
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.net.URLRequest;
	
	import rmhc.api.ApiWrapper;
	import rmhc.api.tasks.IGetProfilePicture;
	
	public class GetProfilePicture extends FbApiTask implements IGetProfilePicture
	{
		protected var gf:FbApiTask;
		protected var lod:Loader;
		
		public function GetProfilePicture(wrapper:ApiWrapper, profileId:String )
		{
			var p:Object = { "fields" : "id,from,type,cover_photo" };
			super(wrapper, profileId + "/albums/" );
		}
		
		override public function parseData(result:Object, fail:Object=null):void
		{
			for each ( var a:Object in result )
			{
				if ( a.type == "profile" )
				{
					//get cover photo
					gf = new FbApiTask( wrapper , a.cover_photo , { "fields" : "source" } );
					gf.addEventListener( Event.COMPLETE , onGetFoto );
					gf.run();
				}
			}
		}
		protected function onGetFoto( e:Event ):void
		{
			var raw:Object = gf.getRawData();
			var req:URLRequest = new URLRequest( raw.source );
			lod = new Loader();
			lod.contentLoaderInfo.addEventListener(Event.COMPLETE , onFotoLoaded );
			lod.load( req , wrapper.getContext() );
		}
		protected function onFotoLoaded( e:Event ):void
		{
			onComplete();
		}
		
		public function getPicture():BitmapData
		{
			return ( lod.content as Bitmap ).bitmapData.clone();
			//return null;
		}
	}
}